<?php


namespace app\index\controller;


use app\index\model\Article;
use app\index\model\Category;
use think\facade\View;

class ListPage extends IndexController {
    protected $redirectList = [3];

    protected function redirectToDetail($categoryId) {
        $lastId = (new Article())->getLastId($categoryId);
        if (!$lastId) {
            $this->redirect(url('/'));
        }
        $this->redirect(url('/index/detail/' . $lastId['id'] . '/' . $lastId['title']));
    }

    public function index() {
        $categoryId = $this->request->param('category_id', 0, 'intval');
        if (in_array($categoryId, $this->redirectList)) {
            $this->redirectToDetail($categoryId);
        }
        $keyword = $this->request->param('keyword', '');

        try {
            [$list, $render] = (new \app\index\model\Article())->getArticleListByCategoryId($categoryId, 15, $keyword);
        } catch (\Exception $e) {
            return show(config('status.error'), $e->getMessage());
        }

        return View::fetch('',
            [
                'category' => $this->category,
                'category_name' => $this->categoryName,
                'bar' => $this->header,
                'banner' => $this->banner,
                'list' => $list,
                'pages' => $render,
                'info' => $this->info,
            ]);
    }

    public function list2() {
        $main_cate_id = $this->request->param('category_id', 0, 'intval');
        $sub_cate_id = $this->request->param('sub_cate_id', 0, 'intval');
        $hasPid = Category::where('pid', $main_cate_id)->field('id')->select()->isEmpty();
        if ($hasPid) {
            return show(config('status.error'), '一级分类下没有找到二级分类');
        }
        $pids = Category::with('child')->field(['id', 'title'])->find($main_cate_id);
        if (empty($sub_cate_id)) {
            $sub_cate_id = $pids['child'][0]['id'];
        }
        [$list, $render] = (new \app\index\model\Article())->getArticleListByCategoryId($sub_cate_id, 12);

//            return show(config('status.error'), 'test', $pids);
        return View::fetch('',
            [
                'category' => $this->category,
                'category_name' => $this->categoryName,
                'category_list' => $pids,
                'sub_cate_id' => $sub_cate_id,
                'bar' => $this->header,
                'banner' => $this->banner,
                'info' => $this->info,
                'list' => $list,
                'pages' => $render,
            ]);
    }
}